package com.imooc.controller;

import com.google.gson.Gson;
import com.imooc.Interceptor.JwtCurrentUserInterceptor;
import com.imooc.base.BaseInfoProperties;
import com.imooc.bo.AdminBO;
import com.imooc.pojo.Admin;
import com.imooc.result.GraceJSONResult;
import com.imooc.result.ResponseStatusEnum;
import com.imooc.service.AdminService;
import com.imooc.utils.JwtUtils;
import com.imooc.vo.AdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * admin管理平台
 * @author liansen
 * @create 02-11-14:12
 */
@RestController
@Validated
@RequestMapping("/admin")
public class AdminController extends BaseInfoProperties {

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public GraceJSONResult login(@RequestBody @Validated AdminBO adminBO){
        boolean isExist = adminService.adminLogin(adminBO);
        if(!isExist){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }
        //获得用户信息
        Admin adminInfo = adminService.getAdminInfo(adminBO);
        String adminJsonString = new Gson().toJson(adminInfo);
        //创建jwt token, 设置过期时间为永不过期
        String adminToken = jwtUtils.createJWTWithPrefix(adminJsonString, TOKEN_ADMIN_PREFIX);
        return GraceJSONResult.ok(adminToken);
    }

    //从ThreadLocal中获取用户信息
    @GetMapping("/info")
    public GraceJSONResult info(){
        Admin admin = JwtCurrentUserInterceptor.adminUser.get();
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);
        return GraceJSONResult.ok(adminVO);
    }

    //退出登录
    @PostMapping("/logout")
    public GraceJSONResult logout(){
        return GraceJSONResult.ok();
    }
}